<template>
  <div class="user">
    <basic-container>
      <el-dialog title="添加用户" :visible.sync="vsible" width="80%">
        <el-row :gutter="20">
          <el-col :span="5">
            <div class="user__tree">
              <avue-tree
                :option="treeOption"
                :data="treeData"
                @node-click="nodeClick"
              >
                <span class="el-tree-node__label" slot-scope="{ node, data }">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="无数据权限"
                    placement="right-start"
                    v-if="data.isLock"
                  >
                    <span>{{ node.label }} <i class="el-icon-lock"></i></span>
                  </el-tooltip>
                  <span v-if="!data.isLock">{{ node.label }}</span>
                </span>
              </avue-tree>
            </div>
          </el-col>
          <el-col :span="8">
            <el-divider content-position="center">组织机构</el-divider>
            <div>
              <el-form :model="formInline" :inline="true" style="display: flex;justify-content: space-between;">
                <el-form-item label="请输入">
                  <el-input v-model="formInline.input" clearable placeholder="支持模糊查询"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="getList">查询</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-form>
            <div class="user__main">
              <el-table
                :data="list"
                ref="tableright"
                stripe
                height="500px"
                border
                v-loading="listLoading"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="username" label="用户" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="ryName" label="姓名" header-align="center" align="center"></el-table-column>
              </el-table>
              <div class="avue-crud__pagination">
                <el-pagination
                  @size-change="sizeChange"
                  @current-change="currentChange"
                  :current-page="page.currentPage"
                  :page-size="page.pageSize"
                  :total="page.total"
                  layout="total, prev, pager, next"
                >
                </el-pagination>
              </div>
            </div>
          </el-col>
          <el-col :span="3" style="text-align: center;line-height: 500px;">
            <el-button type="primary" icon="el-icon-arrow-right" circle @click="pullRight"></el-button>
            <el-button type="danger" icon="el-icon-arrow-left" circle @click="pullLeft"></el-button>
          </el-col>
          <el-col :span="8">
            <el-divider content-position="center">已存在人员</el-divider>
            <el-table
                :data="perlist"
                ref="tableleft"
                stripe
                height="500px"
                style="margin-top:72px;"
                border
                v-loading="listLoading2"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="username" label="用户" header-align="center" align="center"></el-table-column>
                <el-table-column prop="ryName" label="姓名" header-align="center" align="center"></el-table-column>
              </el-table>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onSubmit">确 定</el-button>
          <el-button @click="vsible = false">取 消</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchList,
  getRoleUsers,
} from "@/api/admin/user";
import { deptRoleList, saveRoleAndUsers } from "@/api/admin/role";
import { fetchTree, getTreeList } from "@/api/admin/dept";
import { tableOption } from "@/const/crud/admin/user";
import { remote as remoteDict } from "@/api/admin/dict";
import { mapGetters, mapState } from "vuex";
import store from "@/store";

export default {
  name: "SysUser",
  components: {},
  data() {
    return {
      formInline:{
        input:""
      },
      treeOption: {
        nodeKey: "id",
        addBtn: false,
        menu: false,
        props: {
          label: "name",
          value: "id",
        },
      },
      treeData: [],
      treeListData: [],
      option: tableOption,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false, // 是否倒序
      },
      list: [],
      listLoading: false,
      listLoading2:false,
      role: [],
      perlist: [],
      form: {},
      rolesOptions: [],
      ryZjbm: "",
      userZjOptions: [],
      vsible: false,
      roleId: "",
      deptId:""
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  watch: {
    "form.ryZjbm": {
      handler(val) {
        if (val != "" && val != undefined && val != null) {
          this.userZjOptions.forEach((r) => {
            if (r.value == val) {
              this.form.ryZjmc = r.label;
            }
          });
        } else {
          this.form.ryZjmc = "";
        }
      },
      immediate: true,
    },
    role() {
      this.form.role = this.role;
    },
  },
  created() {
    this.sys_user_add = this.permissions["sys_user_add"];
    this.sys_user_edit = this.permissions["sys_user_edit"];
    this.sys_user_del = this.permissions["sys_user_del"];
  },
  methods: {
    init(roleId) {
      this.vsible = true;
      this.roleId = roleId;
      fetchTree().then((response) => {
        this.treeData = response.data.data;
      });
      getTreeList().then((response) => {
        this.treeListData = response.data.data;
      });
      remoteDict("user_zj").then((response) => {
        this.userZjOptions = response.data.data;
      });
      this.getPerList();
      this.getList();
    },
    getPerList(){
      this.listLoading2 = true;
      getRoleUsers(this.roleId).then((res) => {
        this.perlist = res.data.data;
        this.listLoading2 = false;
      });
    },
    onSubmit() {
      if(this.perlist.length==0){
        this.$message.warning('请选择人员')
        return
      }
      var data = this.perlist;
      var userIds = [];
      if (data.length > 0) {
        data.forEach((item) => {
          userIds.push(item.userId);
        });
      }
      var params = {
        roleId: this.roleId,
        userIds: userIds,
      };
      saveRoleAndUsers(params).then((res) => {
        if (res.data.code == 0) {
          this.$message.closeAll();
          this.$message.success("添加成功!");
          this.vsible = false;
        }
      });
    },
    nodeClick(data) {
      this.page.page = 1;
      this.deptId = data.id
      this.getList();
    },
    getList() {
      this.listLoading = true;
      fetchList({
        current: this.page.currentPage,
        size: this.page.pageSize,
        deptId:this.deptId,
        username:this.formInline.input,
      }).then((response) => {
        this.list = response.data.data.records;
        this.page.total = response.data.data.total;
        this.listLoading = false;
      });
    },
    pullLeft(){
      var data = this.$refs.tableleft.selection;
      if(data.length == 0){
        this.$message.warning('请勾选组织机构表')
      }else{
        for(var i=0; i<data.length; i++){
          for(var j=0; j<this.perlist.length; j++){
            if(data[i].username==this.perlist[j].username){    
              this.perlist.splice(j,1);
              j--;
            }
          }
        }
      }
    },
    pullRight(){
      var rightList = this.$refs.tableright.selection
      if(rightList.length == 0){
        this.$message.warning('请勾已存在人员表')
      }else{
        rightList.forEach(item=>{
           this.perlist.unshift(item)
        })
        this.unique()
      }
    },
    unique(){
      for(var i=0; i<this.perlist.length; i++){
        for(var j=i+1; j<this.perlist.length; j++){
          if(this.perlist[i].username==this.perlist[j].username){
            this.perlist.splice(j,1);
            j--;
          }
        }
      }
    },
    getNodeData() {
      deptRoleList().then((response) => {
        let data = response.data.data;
        if (this.userInfo.username != "admin") {
          for (var i in data) {
            if (data[i].roleCode == "ROLE_ADMIN") {
              data[i].disabled = true;
            }
          }
        }
        this.rolesOptions = data;
      });
    },
    searchChange(param, done) {
      this.page.currentPage = 1;
      done();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
    currentChange(current) {
      this.page.currentPage = current;
      this.getList();
    },
    getDeptDetail(param1, param2) {
      let lResult = "";

      for (let i = 0; i < this.treeListData.length; i++) {
        if (this.treeListData[i].deptId == param1) {
          lResult =
            param2 === "code"
              ? this.treeListData[i].deptCode
              : this.treeListData[i].deptName;
          break;
        }
      }
      return lResult;
    },
  },
};
</script>
<style lang="scss">
.user {
  height: 100%;

  &__tree {
    padding-top: 3px;
    padding-right: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>
